package com.lv.common.ktx

import android.app.Application
import android.content.Context
import android.content.ContextWrapper
import android.content.res.Resources
import android.util.TypedValue
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers

/**
 * 作者： ygx
 * 创建日期：2022/1/20 9:32 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 *      _              _           _     _   ____  _             _ _
 *     / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 *    / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 *   / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 *  /_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * Application相关的ktx扩展
 */


val Application.application: Application
    get() = this

val Float.dp2px: Float
    get() {
        val displayMetrics = Resources.getSystem().displayMetrics
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            this,
            displayMetrics
        )
    }

val Int.dp2px: Int
    get() {
        val displayMetrics = Resources.getSystem().displayMetrics
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            this.toFloat(),
            displayMetrics
        ).toInt()
    }

val Context.toActivity: AppCompatActivity?
    get() {
        if (this is AppCompatActivity) {
            return this
        }

        if (this is ContextWrapper) {
            val baseContext = this.baseContext
            if (baseContext is AppCompatActivity) {
                return baseContext
            }
        }

        return null
    }
val mainScope = CoroutineScope(Dispatchers.Main)

val Context.scope: CoroutineScope
    get() {
        return toActivity?.lifecycleScope ?: mainScope
    }

val Context.scopeOrNull: CoroutineScope?
    get() {
        return toActivity?.lifecycleScope
    }